package com.mkant.home.util;

import com.biletnikov.hotkeys.GlobalKeyboardHook;
import com.biletnikov.hotkeys.GlobalKeyboardListener;

import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.util.List;

import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.plaf.ColorUIResource;

public class Clock extends JFrame implements HotkeyListener {
    private BorderLayout layoutMain = new BorderLayout();
    private JPanel panelCenter = new JPanel();
    private JMenuBar menuBar = new JMenuBar();
    private JMenu menuFile = new JMenu();
    private JMenuItem menuFileExit = new JMenuItem();
    private JMenu menuHelp = new JMenu();
    private JMenuItem menuHelpAbout = new JMenuItem();
    private JLabel statusBar = new JLabel();
    private JToolBar toolBar = new JToolBar();
    private JButton buttonOpen = new JButton();
    private JButton buttonClose = new JButton();
    private JButton buttonHelp = new JButton();
    private ImageIcon imageOpen = 
        new ImageIcon(Clock.class.getResource("openfile.gif"));
    private ImageIcon imageClose = 
        new ImageIcon(Clock.class.getResource("closefile.gif"));
    private ImageIcon imageHelp = 
        new ImageIcon(Clock.class.getResource("help.gif"));
    private JButton jButton1 = new JButton();
    private JLabel jLabel1 = new JLabel();
    private JLabel jLabel2 = new JLabel();

    private boolean isStanding = false;
    private String usrMessage[] = 
        new String[] { "Why aren't you standing?", "You've been standing for..." };
    private Color RED = new Color(235, 63, 59);
    private Color GREEN = new Color(142, 211, 92);
    private Color WHITE = new Color(255, 255, 255);
    private Color GREY = new Color(128, 128, 128);
    Border whiteLine = BorderFactory.createMatteBorder(2, 2, 2, 2, WHITE);
    Border redLine = BorderFactory.createMatteBorder(2, 2, 2, 2, RED);
    Border greenLine = BorderFactory.createMatteBorder(2, 2, 2, 2, GREEN);
    Border redWhiteBorder = 
        BorderFactory.createCompoundBorder(redLine, whiteLine);
    Border greenWhiteBorder = 
        BorderFactory.createCompoundBorder(greenLine, whiteLine);
    private String clockText = "00:00:00";
    private String resetClockText = "00:00:00";
    private boolean runClock = false;
    int hours = 0, minutes = 0, seconds = 0;
    int totalHours = 0, totalMinutes = 0, totalSeconds = 0;
    String totalTimeSpent = "Total Time Spent Standing:  00:00:00";

    Vector<Long> timeList = new Vector<Long>();
    private JLabel jLabel3 = new JLabel();
    private JTabbedPane jTabbedPane1 = new JTabbedPane();

    public Clock() {
        //Use IntelliJ for HotKey support
        // http://code.google.com/p/jintellitype/
        // http://melloware.com/products/jintellitype/quick-start.html
        JIntellitype.getInstance();
        JIntellitype.getInstance().registerHotKey(1, JIntellitype.MOD_WIN, (int)'Q');
        JIntellitype.getInstance().registerHotKey(2, JIntellitype.MOD_WIN, (int)'W');
        JIntellitype.getInstance().addHotKeyListener(this);
        

        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jbInit() throws Exception {

        //        setGradient(GREEN);
        jLabel3.setText("jLabel3");
        jLabel3.setBounds(new Rectangle(10, 235, 295, 25));
        this.setJMenuBar(menuBar);
        this.getContentPane().setLayout(layoutMain);
        panelCenter.setLayout(null);
        panelCenter.setBackground(WHITE);
        this.setSize(new Dimension(400, 400));
        this.setResizable(false);
        this.setTitle("Stand Up or Die Clock");
//        jTabbedPane1.setBounds(new Rectangle(10, 15, 385, 280));

        menuFile.setText("File");
        menuFileExit.setText("Exit");
        menuFileExit.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        fileExit_ActionPerformed(ae);
                    }
                });
        menuHelp.setText("Help");
        menuHelpAbout.setText("About");
        menuHelpAbout.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        helpAbout_ActionPerformed(ae);
                    }
                });

        statusBar.setText("");

        buttonOpen.setToolTipText("Open File");
        buttonOpen.setIcon(imageOpen);
        buttonOpen.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        buttonOpen_actionPerformed(e);
                    }
                });
        buttonClose.setToolTipText("Close File");
        buttonClose.setIcon(imageClose);
        buttonHelp.setToolTipText("About");
        buttonHelp.setIcon(imageHelp);

        //Need to override default L&F for button, see bug 4880747 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4880747
        buttonHelp.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        buttonHelp_actionPerformed(e);
                    }
                });
        jButton1.setContentAreaFilled(false);
        jButton1.setOpaque(true);
        jButton1.setText("Stand Up");
        jButton1.setBackground(GREEN);
        jButton1.setForeground(WHITE);
        jButton1.setBorder(greenWhiteBorder);
        jButton1.setFont(new Font("Monospaced", Font.BOLD, 20));
        jButton1.setBounds(new Rectangle(120, 160, 150, 45));
        jButton1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        jButton1_actionPerformed(e);
                    }
                });

        jLabel1.setText("00:00:00");
        jLabel1.setFont(new Font("Dialog", Font.BOLD, 70));
        jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel1.setHorizontalTextPosition(SwingConstants.CENTER);
        jLabel1.setForeground(GREY);
        jLabel1.setBounds(new Rectangle(50, 75, 290, 75));

        jLabel2.setText(usrMessage[0]);
        jLabel2.setBounds(new Rectangle(65, 25, 255, 30));
        jLabel2.setFont(new Font("Monospaced", Font.ITALIC, 15));
        jLabel2.setForeground(GREY);

        jLabel3.setText(totalTimeSpent);
        jLabel3.setFont(new Font("SansSerif", Font.BOLD|Font.ITALIC, 14));
        jLabel3.setForeground(GREY);

        
        menuFile.add(menuFileExit);
        menuBar.add(menuFile);
        menuHelp.add(menuHelpAbout);
        menuBar.add(menuHelp);

        this.getContentPane().add(statusBar, BorderLayout.SOUTH);
        toolBar.add(buttonOpen);
        toolBar.add(buttonClose);
        toolBar.add(buttonHelp);
        this.getContentPane().add(toolBar, BorderLayout.NORTH);
        
        
        panelCenter.add(jLabel3, null);
        panelCenter.add(jLabel2, null);
        panelCenter.add(jLabel1, null);
        panelCenter.add(jButton1, null);
        jTabbedPane1.addTab("Clock", null, panelCenter, "Clock");
        this.getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
    }

    void fileExit_ActionPerformed(ActionEvent e) {
        JIntellitype.getInstance().cleanUp();
        System.exit(0);
    }

    void helpAbout_ActionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(this, new Clock_AboutBoxPanel1(), 
                                      "About", JOptionPane.PLAIN_MESSAGE);
    }

    private void buttonOpen_actionPerformed(ActionEvent e) {
    }

    private void jButton1_actionPerformed(ActionEvent e) {
        if (!isStanding) {
            setRunClock(true);
            jLabel2.setText(usrMessage[1]);
            isStanding = true;
            jButton1.setText("Sit Down");
            jButton1.setBackground(RED);
            jButton1.setForeground(WHITE);
            jButton1.setBorder(redWhiteBorder);

            (new Thread() {
                    public void run() {
                        long startTime = System.currentTimeMillis();
                        long endTime = 0;
                        long currRun = 0;
                        long sleepDelay = 50;  //ensure that UI updates happen in real time
                        long secondCounts = 1000/sleepDelay;
                        int counter = 0;
                        while(runClock) {
                            counter = 0;
                            while(counter < secondCounts && runClock) {
                                try { Thread.sleep(sleepDelay); } catch(InterruptedException e) {}
                                counter++;
                            }
                            if(counter >= secondCounts)
                                updateClockText(1);
                            jLabel1.setText(clockText);
                            repaint();
                        }
                        
                        updateTotalTimeSpentStanding();
                        setClockText(resetClockText);
                        jLabel1.setText(resetClockText);
                        jLabel3.setText(totalTimeSpent);
                        repaint();
                        hours = minutes = seconds = 0;
                        endTime = System.currentTimeMillis();
                        currRun = endTime-startTime;
                        timeList.add(currRun);
                    }
                }).start();
                
                
        } else {
            setRunClock(false);
            jLabel2.setText(usrMessage[0]);
            jLabel1.setText(resetClockText);
            isStanding = false;
            jButton1.setText("Stand Up");
            jButton1.setBackground(GREEN);
            jButton1.setForeground(WHITE);
            jButton1.setBorder(greenWhiteBorder);


        }

        //        repaint();
    }
    
    public synchronized void setRunClock(boolean val) {
        runClock = val;
    }
    
    public synchronized void setClockText(String clockText) {
        this.clockText = clockText;
    }

    public synchronized void updateClockText(int interval) {
        hours = Integer.parseInt(clockText.substring(0,2));
        minutes = Integer.parseInt(clockText.substring(3,5));
        seconds = Integer.parseInt(clockText.substring(6,8));
        
        seconds += interval;
        
        if(seconds >= 60) {
            seconds -= 60;
            minutes++;
        }
        
        if(minutes >= 60) {
            minutes -= 60;
            hours++;
        }
        
        clockText = getText(hours, minutes, seconds);
        
    }
    
    private synchronized String getText(int hours, int minutes, int seconds) {
        return (hours > 9 ? ""+hours : "0"+hours)
                    + ":" + 
                    (minutes > 9 ? ""+minutes : "0"+minutes)
                    + ":" + 
                    (seconds > 9 ? ""+seconds : "0"+seconds);
    }
    
    public synchronized void updateTotalTimeSpentStanding() {
        totalHours += hours;
        totalMinutes += minutes;
        totalSeconds += seconds;
        
        if(totalSeconds >= 60) {
            totalSeconds -= 60;
            totalMinutes++;
        }
        
        if(totalMinutes >= 60) {
            totalMinutes -=60;
            totalHours++;
        }
        
        String clockText = getText(totalHours, totalMinutes, totalSeconds);
        totalTimeSpent = "Total Time Spent Standing:  " + clockText;
    }
    
    private void toggleWindowState() {
        if(this.getState() == Frame.ICONIFIED) {
            this.setVisible(true);
            this.setState(Frame.NORMAL);
        }
        else {
            this.setState(Frame.ICONIFIED);
            this.setVisible(false);
        }
    }

    public void onHotKey(int key) {
        switch(key) {
            case 1:
                jButton1_actionPerformed(null);
                break;
            case 2:
                toggleWindowState();
                break;
            default:
                System.out.println("Unknown hot key identifier : " + key);
                break;
        }
    }

    private void buttonHelp_actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(this, new Clock_AboutBoxPanel1(), 
                                      "About", JOptionPane.PLAIN_MESSAGE);
    }
}
